import { TOKEN, USER_NAME, USER_INFO } from '@/store/mutation-types'
import { $u } from '@/components/uview-ui'

const user = {
  state: {
    token: '',
    username: '',
    avatar: '',
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    Login ({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        $u.get('/api/user/login.do', {
          user: username,
          pwd: password,
          type: 'username',
          client: 'web',
          basePublic: 'yes'
        }).then(response => {
          if (response.success) {
            const result = response.data
            const userInfo = result.user_info
            $u.storage.set(TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            $u.storage.set(USER_NAME, userInfo.name, 7 * 24 * 60 * 60 * 1000)
            $u.storage.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', userInfo.name)
            resolve(response)
          } else {
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        commit('SET_NAME', '')
        $u.storage.clear()
        $u.post('/api/user/logout.do').then(resolve).catch(resolve)
      })
    }
  }
}

export default user
